/**
 * Copyright (c) 2017, Alex. All rights reserved.
 */
package com.oschina.bottle.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.DefaultRedisCachePrefix;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;

/**
 * 配置类
 *
 * @author <a href="mailto:zhongchao@gegejia.com">zhong</a>
 * @version 1.0 2017/9/28
 * @since 1.0
 */
@EnableCaching
@Configuration
@EnableConfigurationProperties(RedisExtendProperties.class)
@SuppressWarnings("SpringJavaAutowiringInspection")
public class RedisCacheAutoConfiguration extends CachingConfigurerSupport
{
    @Autowired
    private RedisExtendProperties redisExtendProperties;

    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate)
    {
        RedisCacheManager redisCacheManager = new ExtendRedisCacheManager(redisTemplate);
        if(StringUtils.hasText(redisExtendProperties.getPrefix())) {
            String cachePrefix = String.format(":%s:", redisExtendProperties.getPrefix());
            redisCacheManager.setCachePrefix(new DefaultRedisCachePrefix(cachePrefix));
            redisCacheManager.setUsePrefix(true);

        }
        redisCacheManager.setDefaultExpiration(redisExtendProperties.getExpire());
        return redisCacheManager;
    }

    /**
     * redisTemplate
     * keySerializer: StringRedisSerializer
     * valueSerializer: GenericJackson2JsonRedisSerializer
     *
     * 更多的考虑易读性
     *
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return redisTemplate;
    }

    @Override
    public KeyGenerator keyGenerator()
    {
        return new DefaultKeyGenerator();
    }
}
